package com.gec.teams.wechat.controller;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.gec.teams.wechat.annotation.AuthAccess;
import com.gec.teams.wechat.common.FaceComponent;
import com.gec.teams.wechat.common.UpLoadFileComponent;
import com.gec.teams.wechat.config.SystemConstants;
import com.gec.teams.wechat.exception.TeamsException;
import com.gec.teams.wechat.pojo.TbUser;
import com.gec.teams.wechat.pojo.vo.CheckinFormVo;
import com.gec.teams.wechat.pojo.vo.SearchMonthCheckinVo;
import com.gec.teams.wechat.service.CheckinService;
import com.gec.teams.wechat.service.UserService;
import com.gec.teams.wechat.service.impl.UserServiceImpl;
import com.gec.teams.wechat.util.JwtUtil;
import com.gec.teams.wechat.util.R;
import com.gec.teams.wechat.util.SysDateTime;
import com.tencentcloudapi.iai.v20180301.models.VerifyPersonResponse;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.authz.annotation.RequiresUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;

/**
 * 功能：
 * 作者：YumTea
 * 日期：2024/6/19 10:27
 */
@RequestMapping("/checkin")
@RestController
@Api(value = "签到模块业务层",tags = "签到相关接口")
@Slf4j
public class CheckinController {


    @Autowired
    private SysDateTime sysDateTime;
    @Autowired
    private CheckinService checkinService;
    @Autowired
    private UserServiceImpl userService;

    @Autowired
    private FaceComponent faceComponent;
    @Autowired
    private UpLoadFileComponent upLoadFileComponent;
    @Autowired
    private  JwtUtil jwtUtil;

//    @AuthAccess
    @GetMapping("/validCanCheckin")
    @ApiOperation("查看用户今天是否可以签到")
    @RequiresPermissions(value = {"ROOT","USER:INSERT"},logical = Logical.OR)
    public R validCanCheckin(@RequestHeader("token") String token){
        //先把id 从token 里面解析出来
        int userId = jwtUtil.getUserId(token);
        String result = checkinService.validCanCheckin(userId, DateUtil.today());
        return R.ok(result);
    }

    @AuthAccess
    @PostMapping("/uploadFile")
    @ApiOperation("上传图片功能")
//    @RequiresPermissions(value = "{USER:INSERT}")
    public R uploadFile(@RequestParam(value = "file") MultipartFile file){
        upLoadFileComponent.uploadFile(file);
        return R.ok();
    }

    @AuthAccess
    @ApiOperation("创建人脸功能")
    @PostMapping("/createFaceModel")
    public R faceTest(@RequestParam(value = "file") MultipartFile file
            ,@RequestHeader(value ="token") String token
            ,@RequestParam(value = "userName") String name){
//        TODO 还是需要一个判断的，有没有创建成功，要是我就对着地板拍怎么办？
        String userId = String.valueOf(jwtUtil.getUserId(token));
        if(faceComponent.createUser(name, userId,file)) return R.ok();
        return R.error("试试重拍一下吧");
    }
    @AuthAccess
    @ApiOperation("获取人脸功能")
    @PostMapping("/getFaceTest")
    public R getFaceTest(@RequestParam(value = "file") MultipartFile file){
        faceComponent.getUserInfo(Integer.toString(29));
        return R.ok();
    }
    @AuthAccess
    @ApiOperation("获取人脸功能")
    @PostMapping("/checkinFaceTest")
    public R checkinFaceTest(@RequestParam(value = "file") MultipartFile file){
        VerifyPersonResponse verifyPersonResponse = faceComponent.verifyUser(Integer.toString(29), file);
        System.out.println(verifyPersonResponse);
        return R.ok();
    }

    @AuthAccess
    @ApiOperation("签到功能")
    @PostMapping("/checkin")
    public R checkin(@RequestParam(value = "file") MultipartFile file
            , @Valid CheckinFormVo checkinFormVo
            ,@RequestHeader("token") String token){
        Integer userId = jwtUtil.getUserId(token);
        if(ObjectUtil.isEmpty(file)) throw new TeamsException("怎么没传文件过来啊");
        //把这些东西全部放到map里面，个人感觉其实最好还是用DTO来接，但如果只用一次得话用map也可以?
        HashMap map = new HashMap();
        map.put("file",file);
        map.put("userId",userId);
        map.put("form",checkinFormVo);
        checkinService.checkin(map);
        return R.ok();
    }

    @GetMapping("/searchTodayCheckin")
    @ApiOperation("查询用户当日签到数据")
    public R searchTodayCheckin(@RequestHeader("token") String token){
        HashMap map = new HashMap();
        int userId = jwtUtil.getUserId(token);
        //返回的数据map
        //处理一下这个时间段
        map.put("attendanceTime",sysDateTime.work.toString("HH:mm"));
        map.put("closingTime",sysDateTime.down.toString("HH:mm"));
        //累计签到
        long days = checkinService.searchCheckinDays(userId);
        map.put("checkinDays",days);
        //入职日期
        DateTime hiredate=DateUtil.parse(userService.searchUserHiredate(userId));
        DateTime startDate=DateUtil.beginOfWeek(DateUtil.date());
        DateTime endDate = DateUtil.endOfWeek(DateUtil.date());
        //如果在这周三入职，那就从周三开始算
        if(startDate.isBefore(hiredate)) startDate=hiredate;
        HashMap param=new HashMap();
        param.put("startDate",startDate.toString());
        param.put("endDate",endDate.toString());
        param.put("userId",userId);
        ArrayList<HashMap> list=checkinService.searchWeekCheckin(param);
        map.put("weekCheckin",list);
        map.put("checkin",checkinService.searchTodayCheckin(userId));
        return R.ok().put("data",map);
    }

    @PostMapping("/searchMonthCheckin")
    @ApiOperation("查询用户某月签到数据")
    public R searchMonthCheckin(@Valid @RequestBody SearchMonthCheckinVo form, @RequestHeader("token") String token){
        int userId = jwtUtil.getUserId(token);
        DateTime dateTime = DateUtil.parse(userService.searchUserHiredate(userId));
        //月份处理为双数字
        String month = form.getMonth()<10?"0"+form.getMonth():form.getMonth().toString();
        //选择某年某月的第一天
        DateTime startDate = DateUtil.parse(form.getYear() + "-" + month + "-01");
        if(startDate.isBefore(DateUtil.beginOfMonth(dateTime))) throw new TeamsException("只能查询考勤后的数据");
        if(startDate.isBefore(dateTime)) startDate=dateTime;

        //本月结束日期
        DateTime endDate = DateUtil.endOfMonth(startDate);
        HashMap map = new HashMap();
        map.put("userId",userId);
        map.put("startDate",startDate);
        map.put("endDate",endDate);
        ArrayList<HashMap> list=checkinService.searchWeekCheckin(map);
        //统计
        int sum_1=0,sum_2=0,sum_3=0,sum_4=0;
        for (HashMap one : list) {
            String type=one.get("type").toString();
            String status = one.get("status").toString();
            if(!type.equals("工作日")) continue;
            if(status.equals("正常")) sum_1++;
            if(status.equals("迟到")) sum_2++;
            if(status.equals("缺勤")) sum_3++;
            if (status.equals("早退")) sum_4++;
        }
    return R.ok().put("list",list).put("sum_1",sum_1).put("sum_2",sum_2).put("sum_3",sum_3).put("sum_4",sum_4);

    }
}
